package com.mayikt;

import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;

/**
 * @ClassName AtomicTryLock
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class AtomicTryLock {
    private AtomicLong atomicLong = new AtomicLong(0);
    //设计锁 java aqs  持久同一把锁state状态 0 没有线程获取到该锁，获取到该锁的情况下就将state=1

    private Thread lockCurrentThread;

    /**
     * \
     * 获取锁  将内存值改为1
     *
     * @return
     */
    public boolean mayiktTryLock() {
        // V=0 E=0 v==e v 1; result=false
        boolean result = atomicLong.compareAndSet(0, 1);
        if (result) {
            lockCurrentThread = Thread.currentThread();
        }
        return result;
    }

    /**
     * 释放锁 就内存值改为0
     *
     * @return
     */
    public boolean mayiktUnLock() {
        if (lockCurrentThread != null && lockCurrentThread != Thread.currentThread()) {
            return false;
        }
        //v=1 E=1 N=0
        return atomicLong.compareAndSet(1, 0);
    }

    public static void main(String[] args) {
        AtomicTryLock atomicTryLock = new AtomicTryLock();
        IntStream.range(1, 10).forEach((i) -> new Thread(() -> {

            try {
                boolean result = atomicTryLock.mayiktTryLock();
                if (result) {
                    System.out.println(Thread.currentThread().getName() + ",获取锁成功~");
                } else {
                    System.out.println(Thread.currentThread().getName() + ",获取锁失败~");
                }
            } catch (Exception e) {
                e.printStackTrace();
                atomicTryLock.mayiktUnLock();
            } finally {
                atomicTryLock.mayiktUnLock();
            }

        }).start());
    }


}
